package com.cicdi.controller;

import com.cicdi.util.Common;
import com.cicdi.util.Web3jUtil;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;

/**
 * @author haypo
 * @date 2021/3/8
 */
public class ProposalController implements Initializable {
    @FXML
    public TextArea txTextArea;
    @FXML
    public Button getBlockByHashBtn, btn1;
    @FXML
    public TextField hashField, blockNumberLabel;
    @FXML
    public Label text1, packageRewardLabel;

    public void getBlockByHash() {
        if (hashField.getText() != null) {
            getBlockByHashBtn.setDisable(true);
            String blockInfo = Web3jUtil.getBlockByHash(hashField.getText());
            txTextArea.setText(blockInfo);
            getBlockByHashBtn.setDisable(false);
        } else {
            txTextArea.setText("暂无查询结果");
        }
    }

    public void refresh() {//onclick是绑定的按钮的事件
        btn1.setDisable(true);
        text1.setText(Web3jUtil.getAvgPackageTime());
        try {
            blockNumberLabel.setText(Web3jUtil.getBlockNumber().toString(10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        packageRewardLabel.setText(Web3jUtil.getPackageReward());
        btn1.setDisable(false);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //设置平均打包时间
        Common.SCHEDULED_THREAD_POOL_EXECUTOR.scheduleWithFixedDelay(
                () -> Platform.runLater(() -> text1.setText(Web3jUtil.getAvgPackageTime())), 0, 10, TimeUnit.SECONDS);

        //设置打包奖励
        Common.SCHEDULED_THREAD_POOL_EXECUTOR.scheduleWithFixedDelay(
                () -> Platform.runLater(() -> packageRewardLabel.setText(Web3jUtil.getPackageReward())), 0, 10, TimeUnit.SECONDS);
        //定时器的延迟时间及间隔时间，不要设置太小
        Common.SCHEDULED_THREAD_POOL_EXECUTOR.scheduleWithFixedDelay(
                () -> Platform.runLater(() -> {
                    try {
                        blockNumberLabel.setText(Web3jUtil.getBlockNumber().toString(10));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }), 0, 500, TimeUnit.MILLISECONDS);
    }
}
